//
//  SCM3U8SegmentListDownload.m
//  VideoDownloadDemo
//
//  Created by 王琦 on 15/10/19.
//  Copyright (c) 2015年 Riverrun. All rights reserved.
//

#import "SCM3U8SegmentListDownload.h"
#import "SCM3U8SegmentDownload.h"

@interface SCM3U8SegmentListDownload ()<SCM3U8SegmentDownloadDelegate>

@property (strong, nonatomic) NSMutableArray *downloadArray;

@property (nonatomic, copy) NSString *videoUrl;

@end

@implementation SCM3U8SegmentListDownload

- (id)initWithSegmentList:(SCM3U8SegmentList *)segmentList videoUrl:(NSString*)videoUrl
{
    if(self = [super init]){
        self.segmentList = segmentList;
        self.videoUrl = videoUrl;
    }
    return self;
}

- (void)startDownloadVideo
{
    
    if(!_downloadArray){
        self.downloadArray = [NSMutableArray array];
        NSInteger count = [self.segmentList.segments count];
        NSLog(@"下载信息数量：%ld",count);
        for(int i=0;i<count;i++){
            SCM3U8SegmentInfo *segment = [self.segmentList getSegmentWithIndex:i];
            SCM3U8SegmentDownload *segmentDownload = [[SCM3U8SegmentDownload alloc] initWithUrl:segment.url FilePath:self.vid FileName:segment.fileName];
            NSLog(@"TSUrl：%@",segment.url);
            segmentDownload.delegate = self;
            [_downloadArray addObject:segmentDownload];
        }
    }
    if([_downloadArray count]){
        SCM3U8SegmentDownload *firstObj = [_downloadArray firstObject];
        [firstObj start];
    }
}

- (void)pauseDownloadVideo
{
    if([_downloadArray count]){
        SCM3U8SegmentDownload *firstObj = [_downloadArray firstObject];
        [firstObj pause];
    }
}

- (void)cancelDownloadVideo
{
    if([_downloadArray count]){
        SCM3U8SegmentDownload *firstObj = [_downloadArray firstObject];
        [firstObj cancel];
    }
}

- (void)createLocalM3U8File
{
    if(self.segmentList){
        NSString *pathPrefix = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *saveTo = [[pathPrefix stringByAppendingPathComponent:kPathDownload] stringByAppendingPathComponent:self.vid];
        
        NSString *fullPath = [saveTo stringByAppendingPathComponent:@"movie.m3u8"];
        
        NSString *content = [[NSString alloc] initWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:nil];
        //NSLog(@"m3u8---------%@",content);
        NSString *regulaStr = @"\\bhttp?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
        NSError *errorr = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&errorr];
        NSArray *arrayOfAllMatches = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
        for (NSInteger i = 0; i<arrayOfAllMatches.count; i++){
            // NSTextCheckingResult *match = arrayOfAllMatches[i];
            // NSString* substringForMatch = [content substringWithRange:match.range];
            
            // NSArray *array =  [substringForMatch componentsSeparatedByString:@"/"];
            SCM3U8SegmentInfo *segInfo = [self.segmentList getSegmentWithIndex:i];
            content = [content stringByReplacingOccurrencesOfString:segInfo.url withString:segInfo.fileName];
            NSLog(@"匹配的---------%@",segInfo.url);
            [content writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
        }

    }
}

#pragma mark --- SCM3U8SegmentDownloadDelegate ---

- (void)M3U8SegmentDownloadProgress:(CGFloat)progress
{
    CGFloat oneSegmentDownloadProgress = progress*1.0/(float)self.segmentList.segments.count;
    CGFloat totalProgress = (oneSegmentDownloadProgress+(float)(self.segmentList.segments.count-_downloadArray.count)/(float)self.segmentList.segments.count)*100.0;
    if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8SegmentListDownloadProgress:)]){
        [self.delegate M3U8SegmentListDownloadProgress:totalProgress];
    }
}

- (void)M3U8SegmentDownloadFinished:(SCM3U8SegmentDownload *)segmentDownload
{
    [_downloadArray removeObject:segmentDownload];
    if([_downloadArray count]){
        [self startDownloadVideo];
    }
    else{
        [self createLocalM3U8File];
        if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8SegmentListDownloadFinished)]){
            [self.delegate M3U8SegmentListDownloadFinished];
        }
    }
}

- (void)M3U8SegmentDownloadFailed:(SCM3U8SegmentDownload *)segmentDownload
{
    if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8SegmentListDownloadFailed)]){
        [self.delegate M3U8SegmentListDownloadFailed];
    }
}

@end







